package com.example.sbeducation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.sbeducation.dto.HomeworkGradeDTO;
import com.example.sbeducation.dto.HomeworkReviewDTO;
import com.example.sbeducation.dto.HomeworkSubmissionDTO;
import com.example.sbeducation.entity.Homework;
import com.example.sbeducation.entity.HomeworkSubmission;
import com.example.sbeducation.entity.User;
import com.example.sbeducation.exception.BusinessException;
import com.example.sbeducation.mapper.HomeworkSubmissionMapper;
import com.example.sbeducation.service.HomeworkService;
import com.example.sbeducation.service.HomeworkSubmissionService;
import com.example.sbeducation.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 作业提交服务实现类
 */
@Service
public class HomeworkSubmissionServiceImpl extends ServiceImpl<HomeworkSubmissionMapper, HomeworkSubmission>
    implements HomeworkSubmissionService {

  @Autowired
  private HomeworkService homeworkService;

  @Autowired
  private UserService userService;

  @Override
  @Transactional
  public Long submitHomework(HomeworkSubmissionDTO homeworkSubmissionDTO) {
    // 验证作业是否存在
    Homework homework = homeworkService.getHomeworkById(homeworkSubmissionDTO.getHomeworkId());

    // 验证学生是否存在
    User student = userService.getUserById(homeworkSubmissionDTO.getStudentId());
    if (!"student".equals(student.getRole())) {
      throw new BusinessException(400, "只有学生才能提交作业");
    }

    // 验证截止时间
    if (LocalDateTime.now().isAfter(homework.getDeadline())) {
      throw new BusinessException(400, "作业已过截止时间，无法提交");
    }

    // 检查是否已提交过
    HomeworkSubmission existingSubmission = getStudentSubmission(
        homeworkSubmissionDTO.getHomeworkId(),
        homeworkSubmissionDTO.getStudentId());

    HomeworkSubmission submission;
    if (existingSubmission != null) {
      // 更新提交 - 只更新需要的字段，避免使用BeanUtils覆盖附件URL
      submission = existingSubmission;
      submission.setContent(homeworkSubmissionDTO.getContent());
      // 只有当新的附件URL不为空时才更新
      if (homeworkSubmissionDTO.getAttachmentUrl() != null && !homeworkSubmissionDTO.getAttachmentUrl().isEmpty()) {
        submission.setAttachmentUrl(homeworkSubmissionDTO.getAttachmentUrl());
      }
      submission.setSubmitTime(LocalDateTime.now());
      submission.setUpdateTime(LocalDateTime.now());
      submission.setStatus(0); // 重新提交后状态设为未批改
      updateById(submission);
    } else {
      // 新建提交
      submission = new HomeworkSubmission();
      submission.setHomeworkId(homeworkSubmissionDTO.getHomeworkId());
      submission.setStudentId(homeworkSubmissionDTO.getStudentId());
      submission.setContent(homeworkSubmissionDTO.getContent());
      submission.setAttachmentUrl(homeworkSubmissionDTO.getAttachmentUrl());
      submission.setScore(null);
      submission.setComment(null);
      submission.setStatus(0); // 未批改
      submission.setSubmitTime(LocalDateTime.now());
      submission.setCreateTime(LocalDateTime.now());
      submission.setUpdateTime(LocalDateTime.now());
      submission.setDeleted(0);
      save(submission);
    }

    return submission.getId();
  }

  @Override
  @Transactional
  public void gradeHomework(HomeworkGradeDTO homeworkGradeDTO) {
    // 验证提交是否存在
    HomeworkSubmission submission = getSubmissionById(homeworkGradeDTO.getSubmissionId());

    // 更新提交状态
    submission.setScore(homeworkGradeDTO.getScore());
    submission.setComment(homeworkGradeDTO.getComment());
    submission.setStatus(1); // 已批改
    submission.setGradeTime(LocalDateTime.now());
    submission.setUpdateTime(LocalDateTime.now());

    updateById(submission);
  }

  @Override
  @Transactional
  public boolean reviewSubmission(HomeworkReviewDTO reviewDTO) {
    // 验证提交是否存在
    HomeworkSubmission submission = getSubmissionById(reviewDTO.getSubmissionId());

    // 更新提交状态
    submission.setScore(reviewDTO.getScore());
    submission.setComment(reviewDTO.getFeedback());
    submission.setStatus(1); // 已批改
    submission.setGradeTime(LocalDateTime.now());
    submission.setUpdateTime(LocalDateTime.now());

    return updateById(submission);
  }

  @Override
  public HomeworkSubmission getSubmissionById(Long submissionId) {
    HomeworkSubmission submission = getById(submissionId);
    if (submission == null) {
      throw new BusinessException(400, "作业提交不存在");
    }
    return submission;
  }

  @Override
  public Page<HomeworkSubmission> getSubmissionsByHomeworkId(Long homeworkId, Integer page, Integer size) {
    // 验证作业是否存在
    homeworkService.getHomeworkById(homeworkId);

    // 查询提交列表
    Page<HomeworkSubmission> pageParam = new Page<>(page, size);
    LambdaQueryWrapper<HomeworkSubmission> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(HomeworkSubmission::getHomeworkId, homeworkId);
    queryWrapper.orderByDesc(HomeworkSubmission::getSubmitTime);

    return page(pageParam, queryWrapper);
  }

  @Override
  public List<HomeworkSubmissionDTO> getSubmissionsByHomeworkId(Long homeworkId) {
    // 验证作业是否存在
    homeworkService.getHomeworkById(homeworkId);

    // 查询提交列表
    LambdaQueryWrapper<HomeworkSubmission> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(HomeworkSubmission::getHomeworkId, homeworkId);
    queryWrapper.orderByDesc(HomeworkSubmission::getSubmitTime);
    List<HomeworkSubmission> submissions = list(queryWrapper);

    // 转换为DTO并添加学生信息
    return submissions.stream().map(submission -> {
      HomeworkSubmissionDTO dto = new HomeworkSubmissionDTO();
      BeanUtils.copyProperties(submission, dto);

      // 确保attachmentUrl被正确设置
      if (submission.getAttachmentUrl() != null && !submission.getAttachmentUrl().isEmpty()) {
        dto.setAttachmentUrl(submission.getAttachmentUrl());
      }

      // 如果使用feedback字段而非comment字段
      if (submission.getComment() != null) {
        dto.setFeedback(submission.getComment());
      }

      // 获取学生信息
      try {
        User student = userService.getUserById(submission.getStudentId());
        if (student != null) {
          dto.setStudentName(student.getRealName());
        }
      } catch (Exception e) {
        // 忽略获取学生信息失败的情况
      }

      return dto;
    }).collect(Collectors.toList());
  }

  @Override
  public Page<HomeworkSubmission> getSubmissionsByStudentId(Long studentId, Integer page, Integer size) {
    // 验证学生是否存在
    User student = userService.getUserById(studentId);
    if (!"student".equals(student.getRole())) {
      throw new BusinessException(400, "只有学生才能查看自己的作业提交");
    }

    // 查询提交列表
    Page<HomeworkSubmission> pageParam = new Page<>(page, size);
    LambdaQueryWrapper<HomeworkSubmission> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(HomeworkSubmission::getStudentId, studentId);
    queryWrapper.orderByDesc(HomeworkSubmission::getSubmitTime);

    return page(pageParam, queryWrapper);
  }

  @Override
  public HomeworkSubmission getStudentSubmission(Long homeworkId, Long studentId) {
    LambdaQueryWrapper<HomeworkSubmission> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(HomeworkSubmission::getHomeworkId, homeworkId);
    queryWrapper.eq(HomeworkSubmission::getStudentId, studentId);

    return getOne(queryWrapper);
  }
}